<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/activity.php';
require_once $lib_dir.'/friends.php';

$id = null;
if(isset($_REQUEST['id'])){
    $id = $_REQUEST['id'];
}

if((!isset($_SESSION['fb_session']) && !isset($_REQUEST['signed_request'])) || empty($id)){
    print('{ "error": "Invalid request is detected. Program abort." }');
    exit();
}

$facebook = new Facebook(array(
    'appId' => FB_APP_ID,
    'secret' => FB_APP_SECRET
));

if(isset($_SESSION['fb_session'])){
    $facebook->setSession($_SESSION['fb_session']);        
}

$session = $facebook->getSession();

if($session && $id){

    $activities = array();

    try{
        
$now = time();	

        $data = getActivities($id);
    
        //parse in messages
        $inMessageData = getResultSet("inMessageQuery", $data);
        getInMessageActivities($inMessageData, $activities);
      
        //parse out messages
        $outMessageData = getResultSet("outMessageQuery", $data);
        $outThreadData = getResultSet("outThreadQuery", $data);
        getOutMessageActivities($id, $outMessageData, $outThreadData, $activities);
        
        //parse friends' comments
        $friendCommentData = getResultSet("friendCommentQuery", $data);
        getFriendCommentActivities($friendCommentData, $activities);
        
        //parse my comments
        $myCommentData = getResultSet("myCommentQuery", $data);
        getMyCommentActivities($myCommentData, $activities);
        
        //parse friends' posts
        $friendPostData = getResultSet("friendPostQuery", $data);
        getFriendPostActivities($friendPostData, $activities);

    	//sort
    	if(is_array($activities)){
    	    uasort($activities, 'compareTime');
    	}    
		
        //JSON encoding
        $json = "[";
    
        $isFirst = true;
        foreach($activities as $act){
            if(!$isFirst){
                $json .= ',';
            }
            $json .= '{';
            $json .= '"id" : "'.$act->id.'",';
            $json .= '"type" : "'.$act->type.'",';
            $json .= '"name" : "'.$act->name.'",';
            $json .= '"text" : "'.$act->text.'",';
            $json .= '"time" : "'.$act->time.'"';
            $json .= '}';
            $isFirst = false;
        }
    
        $json .= "]";

        $_SESSION["$id"] = $json;
        
        //return output
        print $json;
            
    } catch (Exception $e){
        error_log($e);
        print('{"error":"'.$e->getMessage().'"}');
    }
}